package main;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.swing.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class PropertyLoader {
    private final static String filePath = "resource.properties";
    private Properties Properties;
    private Logger logger = LoggerFactory.getLogger(PropertyLoader.class);

    public PropertyLoader() {
        try {
            defaultLoader();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public PropertyLoader(String filePath) {
        try {
            loader(filePath);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private boolean defaultLoader() throws IOException {
        Properties = new Properties();
        InputStream in = null;
        try {
            in = this.getClass().getClassLoader().getResourceAsStream(filePath);
            Properties.load(in);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                in.close();
            }
        }
        return false;
    }

    private boolean loader(String filePath) throws IOException {
        Properties = new Properties();
        InputStream in = null;
        try {
            File file = new File(filePath);
            if (!file.exists()) {
                logger.error(filePath + "文件未找到");
                return false;
            }
            in = new FileInputStream(file);
            Properties.load(in);
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (in != null) {
                in.close();
            }
        }
        return false;
    }

    public Properties getProperties() {
        return Properties;
    }
}
